package com.defysoft.waukids.slide;

import java.util.Calendar;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.R;

public class Member_Information_A extends BaseActivity implements OnClickListener {
	private SharedPreferences member;	//맴버.
	EditText et[] = new EditText[6];
	TextView tv;
	final int SUCCESS_UPDATE = 10;
	final int FAIL_UPDATE = 9;
	final int UPDATE_INFORMATION = 1;
	Toolbar toolbar;
	Spinner spinner;
	String[] celebrities = {"변경"};
	String birth;
	
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.member_information_a);
		setStartData();
		
	}

	@Override
	public void setStartData() {
		super.setStartData();
		member = getSharedPreferences("member", MODE_PRIVATE);
		et[0] = (EditText)findViewById(R.id.MEMBER_INFORMATION_ET_PASS);	//비밀번호 확인.
		et[1] = (EditText)findViewById(R.id.MEMBER_INFORMATION_ET_NAME);	//이름.
		et[2] = (EditText)findViewById(R.id.MEMBER_INFORMATION_ET_PHONE);	//전화번호.
		et[3] = (EditText)findViewById(R.id.MEMBER_INFORMATION_ET_BIRTH);	//생년월일.
		et[3].setOnClickListener(this);	//생일변경.
		et[4] = (EditText)findViewById(R.id.MEMBER_INFORMATION_ET_REPASS);		//새 비밀번호.
		et[5] = (EditText)findViewById(R.id.MEMBER_INFORMATION_ET_REPASSCHECK);	//새 비밀번호 확인.
		tv = (TextView)findViewById(R.id.MEMBER_INFORMATION_TV_BUTTON);		//정보변경 버튼.
		tv.setOnClickListener(this);
		et[1].setText(member.getString("Mem_Name", ""));
		et[2].setText(member.getString("Mem_Phone", ""));
		et[3].setText(member.getString("Mem_Birth", ""));
		toolbar = (Toolbar)findViewById(R.id.MEMBER_INFORMATION_TOOL);
		spinner = (Spinner)findViewById(R.id.MEMBER_INFORMATION_SPI);
		
		setStartToolbar();
	}

	private void setStartToolbar() {
		spinner.setAdapter(
				new ArrayAdapter<String>(this, 0){
			@Override
			public int getCount() {
				return celebrities.length;
			}
			@Override
			public View getDropDownView(int position, View convertView,
					ViewGroup parent) {
				final int pos = position;
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.overflowitem_row, null);
				}
            ((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
						.setText(celebrities[position]);
				convertView.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						switch (pos) {
						case 0:
							if(et[0].getText().toString().equals("")){
								showPopup("알 림", "기존 비밀번호를 입력해 주세요.", 0);
								return;
							}else if (et[4].getText().toString().equals("") && et[5].getText().toString().equals("")) {
								dialog_Delete(1);
								return;
							} else {
								if (!et[4].getText().toString().equals(et[5].getText().toString()) ) {
									showPopup("알 림", "새 비밀번호와 새 비밀번호 확인정보가 일치하지 않습니다.", 0);
									return;
								}else{
									startNetwork(UPDATE_INFORMATION);
								}
							}
							
							break;
							
						}
					}
				});
				return convertView;
			}

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				final int pos = position;
				if (convertView == null) {
					convertView = getLayoutInflater().inflate(
							R.layout.overflowitem_row, null);
				}
				((TextView) convertView.findViewById(R.id.OVERFLOWITEM_TV))
						.setBackgroundColor(0x00ffffff);
				return convertView;
			}
		});
		
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		/*spinner.setVisibility(View.VISIBLE);*/
		
	}



	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			@Override
			public void run() {
				switch (cho) {
				case UPDATE_INFORMATION:
					updateThread();
					break;

				}
			}
		});
		firstThread.start();
		startDIal();
	}
	private void updateThread(){
		JSONObject jsonObject = null;
		try {
			jsonObject = new JSONObject(publicHttpCallback(HTTP_MEMBERINFORMATION_UPDATE,
					"PK_Mem_Email="+member.getString("PK_Mem_Email", "")+"&Mem_Pass="+et[0].getText().toString()
					+"&Mem_Name="+et[1].getText().toString()+"&Mem_Phone="+et[2].getText().toString()
					+"&Mem_Birth="+et[3].getText().toString()+"&Mem_PassRe="+et[4].getText().toString()));
			if(jsonObject.getBoolean("success")){
				onNetworkCallback(SUCCESS_UPDATE, "");
			}else{
				onNetworkCallback(FAIL_UPDATE, jsonObject.getString("message"));
			}
		} catch (JSONException e) {
				onNetworkCallback(CATCH_EXCEPTION, e.toString());
		}
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		switch (_message.what) {
		case CATCH_EXCEPTION: // thread 에러 메세지
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			Toast.makeText(this, (String) _message.obj, Toast.LENGTH_LONG).show();
			break;
		case SUCCESS_UPDATE:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			Toast.makeText(this, "정보수정을 완료하였습니다.", Toast.LENGTH_SHORT).show();
			break;
		case FAIL_UPDATE:
			endDIal();
			if (firstThread != null) {firstThread.interrupt();}
			Toast.makeText(this, _message.obj.toString(), Toast.LENGTH_SHORT).show();			
			break;
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.MEMBER_INFORMATION_TV_BUTTON:
			if(et[0].getText().toString().equals("")){
				showPopup("알 림", "기존 비밀번호를 입력해 주세요.", 0);
				return;
			}else if (et[4].getText().toString().equals("") && et[5].getText().toString().equals("")) {
				dialog_Delete(1);
				return;
			} else {
				if (!et[4].getText().toString().equals(et[5].getText().toString()) ) {
					showPopup("알 림", "새 비밀번호와 새 비밀번호 확인정보가 일치하지 않습니다.", 0);
					return;
				}else{
					startNetwork(UPDATE_INFORMATION);
				}
			}
			
			break;
		case R.id.MEMBER_INFORMATION_ET_BIRTH:
			DialogBirthPicker();
			
			break;

		}
	}

	void dialog_Delete(final int pos1) {	//예,아니오 버튼
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("비밀번호 변경없이 정보수정 하겠습니까.").setCancelable(false)
              .setPositiveButton("네", new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
 					startNetwork(UPDATE_INFORMATION);
                     dialog.cancel();
                 }
              })
              .setNegativeButton("아니오", new DialogInterface.OnClickListener() {
                 @Override
                 public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                 }
              });
        AlertDialog alert = builder.create();
        alert.show();
     } 
	
	private void DialogBirthPicker() {	//생일수정
		Calendar c = Calendar.getInstance();
		int cyear = c.get(Calendar.YEAR);
		int cmonth = c.get(Calendar.MONTH);
		int cday = c.get(Calendar.DAY_OF_MONTH);
		
		DatePickerDialog.OnDateSetListener mDateSetListener = new OnDateSetListener() {
			@Override
			public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
	    	  	String month= (monthOfYear+1)+"";
	    	  	if(month.length()==1){
	    	  		month= "0"+month;
	    	  	}
		    	birth = year+""+month+""+dayOfMonth;
		    	et[3].setText(birth);
		    	et[3].setTextColor(Color.BLACK);	
			}
		};
		new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday).show();
	}
	
}//CLASS_END
